import xml.etree.ElementTree as ET

sets = [('2007', 'LS_train'), ('2007', 'LS_val'), ('2007', 'LS_test')]
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle",
           "bus", "car", "cat", "chair", "cow", "diningtable",
           "dog", "horse", "motorbike", "person", "pottedplant",
           "sheep", "sofa", "train", "tvmonitor"]
# len(classes) = 20


def convert_annotation(year, img_id, list_file):
    list_file.write("VOCdevkit/VOC%s/JPEGImages/%s.jpg" % (year, img_id))
    # 读取VOC数据集中对应的XML标识的数据。
    in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml' % (year, img_id))
    # 获取XML中的最根部的标签
    root = ET.parse(in_file).getroot()

    # 循环便利root里面包含的所有的object也就是我们需要检测的物体。
    for obj in root.iter('object'):
        # 这个标识用于判断这个目标检测是不是较为困难。
        difficult = obj.find('difficult').text
        # 获得目标类别名称
        cls = obj.find('name').text
        if cls not in classes or int(difficult) == 1:
            continue
        # 获取类别对应的类别ID
        cls_id = classes.index(cls)
        # 获取的目标标注的BOX
        xml_box = obj.find('bndbox')
        b = (int(xml_box.find('xmin').text),
             int(xml_box.find('ymin').text),
             int(xml_box.find('xmax').text),
             int(xml_box.find('ymax').text))
        list_file.write(" " + ','.join([str(i) for i in b]) + ',' + str(cls_id))


for year, img_set in sets:
    img_ids = open('./Main/%s.txt' % img_set).read().strip().split()
    list_file = open('%s_%s.txt' % (year, img_set), 'w')
    for img_id in img_ids:
        convert_annotation(year, img_id, list_file)
        list_file.write('\n')
    list_file.close()
